

class TopicController extends SecureController{
    def authenticateService
    def topicService

    static navigation = [
        group:'topics', action:'index', title:'频道中心', order: 1,
        subItems:[
            [action:'index',title:'进行中',order:11],
            [action:'index2',title:'发起中',order:12],
            [action:'index3',title:'历史精华',order:13],
            [action:'create',title:'发起新话题',order:14]
        ]
    ]

	
    def index = {
        params.status = 'START'
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ topicInstanceList: topicService.getTopic(params.status,params), topicInstanceTotal: Topic.countByStatus(params.status) ]
    }

    def index2 = {
        params.status = 'INIT'
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)

        [ topicInstanceList: topicService.getTopic(params.status,params), topicInstanceTotal: Topic.countByStatus(params.status) ]
    }

    def index3 = {
        params.status = 'END'
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)

        [ topicInstanceList: topicService.getTopic(params.status,params), topicInstanceTotal: Topic.countByStatus(params.status) ]
    }
	
    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']
	
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        
        [ topicInstanceList: topicService.getTopic(params), topicInstanceTotal: Topic.count() ]
    }
	
    def show = {
        def topicInstance = Topic.get( params.id )
		
        if(!topicInstance) {
            flash.message = "没有找到对应的讨论话题"
            redirect(action:list)
        } else {
            def topicUsers = TopicUser.findAllByTopic(topicInstance)
            return [ topicInstance : topicInstance , topicUsers : topicUsers]
        }
    }
	
    def delete = {
        //        def topicInstance = Topic.get( params.id )
        //        if(topicInstance) {
        //            try {
        //                topicInstance.delete(flush:true)
        //                flash.message = "Topic ${params.id} deleted"
        //                redirect(action:list)
        //            }
        //            catch(org.springframework.dao.DataIntegrityViolationException e) {
        //                flash.message = "Topic ${params.id} could not be deleted"
        //                redirect(action:show,id:params.id)
        //            }
        //        }
        //        else {
        //            flash.message = "Topic not found with id ${params.id}"
        //            redirect(action:list)
        //        }
    }
	
    def edit = {
        //        def topicInstance = Topic.get( params.id )
        //
        //        if(!topicInstance) {
        //            flash.message = "Topic not found with id ${params.id}"
        //            redirect(action:list)
        //        }
        //        else {
        //            return [ topicInstance : topicInstance ]
        //        }
    }
	
    def update = {
        //        def topicInstance = Topic.get( params.id )
        //        if(topicInstance) {
        //            if(params.version) {
        //                def version = params.version.toLong()
        //                if(topicInstance.version > version) {
        //
        //                    topicInstance.errors.rejectValue("version", "topic.optimistic.locking.failure", "Another user has updated this Topic while you were editing.")
        //                    render(view:'edit',model:[topicInstance:topicInstance])
        //                    return
        //                }
        //            }
        //            topicInstance.properties = params
        //            if(!topicInstance.hasErrors() && topicInstance.save()) {
        //                flash.message = "Topic ${params.id} updated"
        //                redirect(action:show,id:topicInstance.id)
        //            }
        //            else {
        //                render(view:'edit',model:[topicInstance:topicInstance])
        //            }
        //        }
        //        else {
        //            flash.message = "Topic not found with id ${params.id}"
        //            redirect(action:list)
        //        }
    }
	
    def create = {
        def topicInstance = new Topic()
        topicInstance.properties = params
        return ['topicInstance':topicInstance]
    }
	
    def save = {
        def topicInstance = new Topic(params)
		
        def loginUser = session.user

        try{
            def topic = topicService.createTopic(loginUser.id, topicInstance)
            flash.message = "Topic ${topicInstance.id} created"
            redirect(action:show,id:topicInstance.id)
        } catch (TopicException e) {
            flash.message  = e.message
            render(view:'create',model:[topicInstance:topicInstance])
        }
        
    }
	
    def joinAsSpeaker = {
        if(isLoggedIn()){
            def user = session.user
            def topic = Topic.get(params.id)

            try{
                topicService.addSpeaker(topic, user)
                flash.message = "成功加入话题［${topic}］，你可以发言啦"
                redirect(action:show,id:topic.id)
            } catch(TopicException te) {
                flash.message = te.message
                redirect(action:show,id:topic.id)
            }
        } else {
            redirect(controller:'login',action:'auth')
        }
        
    }

    def joinAsViewer = {
        if(isLoggedIn()){
            def user = session.user
            def topic = Topic.get(params.id)

            try{
                topic = topicService.addViewer(topic, user)
                flash.message = "你已经成为话题［${topic}］的观众啦"
                redirect(action:show,id:topic.id)
            } catch(TopicException te) {
                flash.message = te.message
                redirect(action:show,id:topic.id)
            }
        } else {
            redirect(controller:'login',action:'auth')
        }
    }

    def renderImage = {
        def topic = Topic.get(params.id)
        if(topic?.image) {
            response.setContentLength(topic.image.length)
            response.outputStream.write(topic.image)
        } else {
            response.sendError(404)
        }
    }

    /**
     * Check if logged in.
     */
    private boolean isLoggedIn() {
        return authenticateService.isLoggedIn()
    }

    private boolean isAjax() {
        return authenticateService.isAjax(request)
    }
}
